package com.cloudknow.activity;


import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.cloudknow.Base.BasePresenter;
import com.cloudknow.Base.BaseView;
import com.cloudknow.common.CommonConstant;
import com.cloudknow.common.R;
import com.cloudknow.dialogs.CustomProgressDialog;
import com.cloudknow.manager.ActivityManager;
import com.cloudknow.manager.MyApplication;
import com.cloudknow.utils.FixMemLeakUtils;
import com.cloudknow.utils.PrefsUtil;
import com.cloudknow.utils.StatusBarUtil;
import com.cloudknow.utils.TUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity  {
    private static final String TAG = BaseActivity.class.getSimpleName();

    protected Context context;
    protected Activity activity;

    private CustomProgressDialog pd;

    protected enum STATE {REFRESH, LOADMORE}

    protected STATE scrollState = STATE.REFRESH;

    protected String uid = "";
    protected String token = "";

    public Activity instans;

    private WeakReference<Activity> weakReference = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //根据不同的页面设置不同的xml布局
        setContentView(setView());
        //ButterKnife初始化，子页面可以不用再次初始化
        ButterKnife.bind(this);
        fullScreen(this);

        //上下文尽早赋值，避免拿不到报空指针
        context = this;
        activity = this;
        instans = this;

        // 注册,
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }
        //将activity添加到管理列表中
        if (weakReference == null) {
            weakReference = new WeakReference<Activity>(this);
        }

        uid = PrefsUtil.getString(context, CommonConstant.UID);
        token = PrefsUtil.getString(context, CommonConstant.TOKEN);

        initialize();
        // 子类中需要获取Activity异常销毁时的值的时候使用
        initState(savedInstanceState);

        //将activity添加到集合中，退出登录时（或其他地方）需要用到

        ActivityManager.getInstance().addActivity(weakReference.get());


    }


    // 当页面因为异常销毁需要保存数据时调用该方法
    protected void initState(Bundle savedInstanceState) {

    }



    /**
     * 设置Activity要显示的布局
     *
     * @return 布局的layoutId
     */
    protected abstract int setView();

    private void initialize() {
        //三者的调用顺序不能出错
        receiveData();

        initializeView();

        loadDataFromServer();
    }

    /**
     * 接收数据
     */
    protected abstract void receiveData();

    /**
     * 视图初始化，使用了ButterKnife所以一般用不到，但是可以初始化其他的
     */
    protected abstract void initializeView();

    /**
     * 调用服务端的接口
     */
    protected abstract void loadDataFromServer();

    /**
     * 以下都是和申请权限有关
     */
    private int REQUEST_CODE_PERMISSION = 0x00099;

    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission4Base(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(this,
                    needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();
            }
        }
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }


    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        Log.d(TAG, "获取权限成功=" + requestCode);
    }

    /**
     * 权限获取失败
     *
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        Log.d(TAG, "获取权限失败=" + requestCode);
    }

    /**
     * 以上都是和申请权限有关
     */


    /**
     * 跳转activity,不带参数
     */
    public void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    /**
     * 跳转activity 带参数
     */
    public void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消注册
//        EventBus.getDefault().unregister(this);
        //将activity从列表中移除
        ActivityManager.getInstance().removeActivity(weakReference.get());
        // 处理华为手机mlastsrvview内存泄露问题
        FixMemLeakUtils.fixLeak(MyApplication.getApplication());


    }

    /**
     * 显示dialog
     */
    public void showProgressDialog() {

        try {
            if (null == pd) {
                pd = new CustomProgressDialog();
            }
            if (!pd.isAdded() && !pd.isVisible() && !pd.isRemoving()) {

                FragmentTransaction ft = getFragmentManager().beginTransaction();

                /*
                 * 如果不执行remove()，对话框即不会进入onDismiss()状态。会被显示在新的对话框下方，是可见的。
                 * 主要考虑美观的问题，如果下面的对话框大于上面的对话框就很难看了。 对于Dialog，container为0或者null。
                 */
//                ft.remove();
                /*
                 * 将当前的PromptDialogFragment加入到回退堆栈，当用户按返回键，或者通过按帮助框的Close按钮dismiss帮助框是，
                 * 重新显示提示框。 对于back stack的处理，系统具有一定的智能。例如：执行两次addToStackStack()，实际不会重复压栈。
                 * 有例如：注释掉remove()语句，即提示框不消失，而是在帮助框的下面。
                 * 但是在实验中发现是否有addToBackStack()都不会结果有影响，系统能够分析到对象存在，不需要压栈。没有去查源代码，
                 * 猜测通过mBackStackId比对来进行智能处理。
                 */
                ft.addToBackStack(null);
                pd.show(getSupportFragmentManager(), "CustomProgressDialog");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消dialog
     */
    public void hideProgressDialog() {
        if (null != pd) {
            pd.dismiss();
        }
    }



    /**
     * 通过设置全屏，设置状态栏透明
     *
     * @param activity
     */
    private void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }




    /**
     * 获取状态栏高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return getResources().getDimensionPixelSize(resourceId);
        }
        return 0;
    }


    /**
     * 重写getResources()方法，让APP的字体不受系统设置字体大小影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
